<template>
  <div class="user-profile-container">
    <!-- 顶部用户信息卡片 -->
    <div class="profile-header">
      <div class="header-bg"></div>
      <div class="header-content container">
        <div class="user-card">
          <div class="avatar-container">
            <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar" class="user-avatar"></el-avatar>
            <div class="avatar-actions">
              <el-upload
                class="upload-wrapper"
                action="#"
                :show-file-list="false"
                :http-request="handleAvatarUpload"
                accept="image/*">
                <div class="upload-mask">
                  <el-icon class="upload-icon"><Camera /></el-icon>
                </div>
              </el-upload>
            </div>
          </div>
          <div class="user-info">
            <h1 class="user-name">{{ userInfo.name }}</h1>
            <p class="user-username">@{{ userInfo.username }}</p>
            <div class="user-role" :class="getRoleClass(userInfo.roles)">{{ formatRoles(userInfo.roles) }}</div>
            <p class="user-join-date">
              <el-icon><Calendar /></el-icon>
              <span>注册于 {{ userInfo.createTime}}</span>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户资料内容区域 -->
    <div class="profile-content container">
      <el-card class="main-card">
        <el-tabs>
          <el-tab-pane label="个人资料">
            <div class="info-section">
              <div class="section-title">基本信息</div>
              <el-divider></el-divider>
              
              <div v-if="!isEditing">
                <div class="info-grid">
                  <div class="info-item">
                    <span class="info-label">用户ID</span>
                    <span class="info-value">{{ userInfo.id }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">昵称</span>
                    <span class="info-value">{{ userInfo.name }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">用户名</span>
                    <span class="info-value">{{ userInfo.username }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">邮箱</span>
                    <span class="info-value">{{ userInfo.email }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">注册时间</span>
                    <span class="info-value">{{ userInfo.createTime }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">修改时间</span>
                    <span class="info-value">{{ userInfo.updateTime }}</span>
                  </div>
                </div>
                
                <div class="action-buttons">
                  <el-button type="primary" @click="startEdit" class="action-btn">
                    <el-icon><Edit /></el-icon>
                    <span>编辑资料</span>
                  </el-button>
                  <el-button @click="showChangePasswordDialog" class="action-btn password-btn">
                    <el-icon><Lock /></el-icon>
                    <span>修改密码</span>
                  </el-button>
                </div>
              </div>
              
              <el-form 
                v-else 
                :model="editForm" 
                :rules="editRules" 
                ref="editFormRef"
                label-position="top"
                class="edit-form">
                <el-form-item label="昵称" prop="name">
                  <el-input v-model="editForm.name" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item>
                  <div class="form-actions">
                    <el-button type="primary" @click="updateProfile" :loading="updateLoading" class="action-btn">保存</el-button>
                    <el-button @click="cancelEdit" class="action-btn">取消</el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="info-section" v-if="userInfo.ipInfo">
              <div class="section-title">登录信息</div>
              <el-divider></el-divider>
              <div class="ip-info">
                <div class="ip-item">
                  <el-icon><Location /></el-icon>
                  <span class="ip-text">IP地址：{{ userInfo.ipInfo.ip }}</span>
                </div>
                <div class="ip-item" v-if="userInfo.ipInfo.country || userInfo.ipInfo.province || userInfo.ipInfo.city">
                  <el-icon><MapLocation /></el-icon>
                  <span class="ip-text">
                    位置：{{ userInfo.ipInfo.country === '0' ? '' : userInfo.ipInfo.country }}
                    {{ userInfo.ipInfo.province === '0' ? '' : userInfo.ipInfo.province }}
                    {{ userInfo.ipInfo.city }}
                  </span>
                </div>
                <div class="ip-item" v-if="userInfo.ipInfo.businessOperator">
                  <el-icon><Connection /></el-icon>
                  <span class="ip-text">网络：{{ userInfo.ipInfo.businessOperator }}</span>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
        </el-tabs>
      </el-card>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="changePasswordVisible" title="修改密码" width="400px">
      <el-form :model="passwordForm" label-position="top" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入当前密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="changePasswordVisible = false" class="dialog-btn">取消</el-button>
          <el-button type="primary" @click="updatePasswordBtn" :loading="passwordLoading" class="dialog-btn">
            修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getUserInfoById, updateUserInfo,updatePassword } from '../api/user.js'
import { uploadFile } from '../api/file.js'
import { useTokenStore, useUserStore } from '../stores/index'
import { useRoute, useRouter } from 'vue-router'
import { 
  User, Calendar, Edit, Lock, Camera, Location, 
  MapLocation, Connection
} from '@element-plus/icons-vue'

// 路由和状态
const route = useRoute()
const router = useRouter()
const tokenStore = useTokenStore()
const userStore = useUserStore()
const userId = computed(() => route.params.id)

// 数据状态
const userInfo = ref({})
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
const isEditing = ref(false)

// 对话框状态
const changePasswordVisible = ref(false)
const updateLoading = ref(false)
const passwordLoading = ref(false)

// 表单引用
const editFormRef = ref(null)
const passwordFormRef = ref(null)

// 表单数据
const editForm = ref({
  name: '',
  email: ''
})

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})


// 表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 密码验证
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 初始化
onMounted(async () => {
  await fetchUserInfo()
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfoById(userId.value)
    if (res.code === 200 && res.data) {
      userInfo.value = res.data
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
    ElMessage.error('获取用户信息失败')
  }
}


// 格式化角色
const formatRoles = (roles) => {
  if (!roles || roles.length === 0) return '普通用户'
  
  const roleMap = {
    'admin': '管理员',
    'common': '普通用户',
  }
  
  return roles.map(role => roleMap[role] || role).join(', ')
}

// 获取角色样式类
const getRoleClass = (roles) => {
  if (!roles || roles.length === 0) return 'role-common'
  
  if (roles.includes('admin')) return 'role-admin'
  if (roles.includes('vip')) return 'role-vip'
  return 'role-common'
}

// 开始编辑
const startEdit = () => {
  editForm.value.name = userInfo.value.name
  editForm.value.email = userInfo.value.email
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
}

// 显示修改密码对话框
const showChangePasswordDialog = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  changePasswordVisible.value = true
}

// 更新个人资料
const updateProfile = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      updateLoading.value = true
      try {
        // 调用API更新用户信息
        const userData = {
          id: userInfo.value.id,
          name: editForm.value.name,
          email: editForm.value.email
        }
        
        const res = await updateUserInfo(userData)
        
        if (res.code === 200) {
          // 更新当前页面显示的用户信息
          userInfo.value.name = editForm.value.name
          userInfo.value.email = editForm.value.email
          
          // 同时更新Pinia中的用户信息状态
          userStore.updateUserInfoState({
            name: editForm.value.name,
            email: editForm.value.email
          })
          
          ElMessage.success('个人资料更新成功')
          isEditing.value = false
        } else {
          ElMessage.error(res.msg || '更新个人资料失败')
        }
      } catch (error) {
        console.error('更新个人资料出错:', error)
        ElMessage.error('更新个人资料失败')
      } finally {
        updateLoading.value = false
      }
    }
  })
}

// 更新密码
const updatePasswordBtn = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        // 调用API修改密码
        const passwordData = {
          id: userInfo.value.id,
          username: userInfo.value.username,
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        }
        
        const res = await updatePassword(passwordData)
        
        if (res.code === 200) {
          ElMessage.success('密码修改成功')
          changePasswordVisible.value = false
        } else {
          ElMessage.error(res.msg || '修改密码失败')
        }
      } catch (error) {
        console.error('修改密码出错:', error)
        ElMessage.error('修改密码失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 处理头像上传
const handleAvatarUpload = async (options) => {
  try {
    const file = options.file
    // 验证文件类型和大小
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
    
    if (!isImage) {
      ElMessage.error('只能上传图片文件!')
      return
    }
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过 2MB!')
      return
    }
    
    // 上传头像文件
    uploadFile(file, 5).then(res => {
      if (res.code === 200 && res.data) {
        // 更新头像URL
        userInfo.value.avatar = res.data
        
        // 调用API更新用户信息
        const userData = {
          id: userInfo.value.id,
          avatar: res.data
        }
        
        // 同时更新Pinia中的用户信息状态
        userStore.updateUserInfoState({ avatar: res.data })
        
        return updateUserInfo(userData)
      } else {
        ElMessage.error(res.msg || '头像上传失败')
        return Promise.reject('头像上传失败')
      }
    }).then(updateRes => {
      if (updateRes.code === 200) {
        ElMessage.success('头像更新成功')
      } else {
        ElMessage.error(updateRes.msg || '用户信息更新失败')
      }
    }).catch(error => {
      console.error('处理头像上传出错:', error)
      ElMessage.error('头像更新失败')
    })
  } catch (error) {
    console.error('上传头像出错:', error)
    ElMessage.error('头像上传失败')
  }
}
</script>

<style scoped>
.user-profile-container {
  min-height: calc(100vh - 64px - 100px);
  background-color: var(--color-background);
}

/* 顶部个人资料卡片 */
.profile-header {
  position: relative;
  padding: 40px 0 30px;
  margin-bottom: 30px;
  overflow: hidden;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 180px;
  background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-primary-light) 100%);
  opacity: 0.8;
  z-index: 0;
}

.header-content {
  position: relative;
  z-index: 1;
}

.user-card {
  background-color: var(--color-card);
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 30px;
}

.avatar-container {
  position: relative;
}

.user-avatar {
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-actions {
  position: absolute;
  bottom: 0;
  right: 0;
  z-index: 2;
}

.upload-wrapper {
  width: 100%;
  height: 100%;
}

.upload-mask {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: var(--color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-mask:hover {
  transform: scale(1.1);
  background-color: var(--color-primary-dark);
}

.upload-icon {
  font-size: 16px;
}

.user-info {
  flex: 1;
}

.user-name {
  margin: 0 0 5px;
  font-size: 1.8rem;
  color: var(--color-text);
}

.user-username {
  margin: 0 0 10px;
  color: var(--color-text-light);
  font-size: 0.95rem;
}

.user-role {
  display: inline-block;
  font-size: 0.8rem;
  padding: 3px 10px;
  border-radius: 12px;
  margin-bottom: 10px;
}

.role-admin {
  background-color: #f56c6c;
  color: white;
}

.role-vip {
  background-color: #e6a23c;
  color: white;
}

.role-common {
  background-color: #909399;
  color: white;
}

.user-join-date {
  margin: 5px 0 0;
  color: var(--color-text-light);
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 内容区域 */
.profile-content {
  padding-bottom: 50px;
}

.main-card {
  margin-bottom: 20px;
}

.info-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 1.1rem;
  font-weight: 500;
  color: var(--color-text);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-bottom: 25px;
}

.info-item {
  padding: 10px;
  border-radius: 8px;
  background-color: var(--color-background);
}

.info-label {
  display: block;
  color: var(--color-text-light);
  font-size: 0.85rem;
  margin-bottom: 5px;
}

.info-value {
  color: var(--color-text);
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.action-btn {
  border-radius: 8px;
  padding: 8px 16px;
  transition: all 0.3s;
  font-weight: 500;
  width: 120px;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.password-btn {
  background-color: var(--color-background);
  border-color: var(--color-border);
  color: var(--color-text);
}

.password-btn:hover {
  background-color: #f5f7fa;
  color: var(--color-primary);
}

.edit-form {
  max-width: 500px;
}

.form-actions {
  display: flex;
  gap: 10px;
}

.ip-info {
  padding: 15px;
  background-color: var(--color-background);
  border-radius: 8px;
}

.ip-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.ip-item:last-child {
  margin-bottom: 0;
}

.ip-text {
  color: var(--color-text);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-btn {
  width: 80px;
  border-radius: 8px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .user-card {
    flex-direction: column;
    text-align: center;
    padding: 20px;
  }
  
  .user-join-date {
    justify-content: center;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>
